package com.ext.aic.apis;

import android.content.Context;

import com.ext.aic.R;
import com.ext.aic.beans.response.Response;
import com.ext.aic.constants.ApiConstants;
import com.ext.aic.constants.EBusConstants;
import com.ext.aic.utils.LoadingUtils;
import com.ext.aic.utils.ToastyUtils;
import com.eyinfo.android_pure_utils.ebus.EBus;
import com.eyinfo.android_pure_utils.logs.Logger;
import com.hjq.http.config.IRequestApi;
import com.hjq.http.exception.ResponseException;
import com.hjq.http.listener.OnHttpListener;

import java.util.Arrays;
import java.util.List;

public abstract class RequestResponse<T> implements OnHttpListener<T> {

    private Context context;
    private boolean isShowLoading;
    private String currentApi;
    private List<String> exclusionApis = Arrays.asList(ApiPaths.refreshToken, ApiPaths.login, ApiPaths.logout, ApiPaths.register);
    private int loadingResId;

    public RequestResponse(Context context, boolean isShowLoading, int loadingResId) {
        this.context = context;
        this.isShowLoading = isShowLoading;
        this.loadingResId = loadingResId;
    }

    public RequestResponse(Context context, boolean isShowLoading) {
        this(context, isShowLoading, 0);
    }

    protected abstract void onSuccess(T t);

    @Override
    public void onHttpStart(IRequestApi api) {
        currentApi = api.getApi();
        if (isShowLoading) {
            LoadingUtils.showLoading(context, loadingResId == 0 ? R.string.loading : loadingResId);
        }
    }

    @Override
    public void onHttpSuccess(T t) {
        onSuccess(t);
        if (!exclusionApis.contains(currentApi) && t instanceof Response) {
            Response response = (Response) t;
            if (ApiConstants.unauthorized.contains(response.getCode())) {
                authorizationFailureInterception();
            }
        }
    }

    @Override
    public void onHttpFail(Throwable throwable) {
        if (currentApi.contains(ApiPaths.auditStatus)) {
            return;
        }
        Logger.error(throwable);
        if (!exclusionApis.contains(currentApi) && throwable instanceof ResponseException) {
            ResponseException exception = (ResponseException) throwable;
            okhttp3.Response response = exception.getResponse();
            if (response != null && ApiConstants.unauthorized.contains(response.code())) {
                authorizationFailureInterception();
            }
        } else {
            ToastyUtils.getInstance().show(context.getString(R.string.server_exception_tip));
        }
    }

    @Override
    public void onHttpEnd(IRequestApi api) {
        LoadingUtils.hideLoading();
    }

    private void authorizationFailureInterception() {
        EBus.getInstance().post(EBusConstants.unauthorized);
    }
}
